package com.example.qsindusty.jmm_spline.OrderinfoActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.ContralFragment.ControlService;
import com.example.qsindusty.jmm_spline.MainActivity;
import com.example.qsindusty.jmm_spline.OrdeFragment.OrderData;
import com.example.qsindusty.jmm_spline.PicActivity;
import com.example.qsindusty.jmm_spline.R;
import com.example.qsindusty.jmm_spline.api.ApiManager;
import com.yixin.ystartlibrary.base.BaseAppCompatActivity;
import com.yixin.ystartlibrary.base.BaseRecyclerAdapter;
import com.yixin.ystartlibrary.utils.DensityUtil;
import com.yixin.ystartlibrary.utils.DialogUtils;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.ImageUtil;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.StatusBarUtil;
import com.yixin.ystartlibrary.utils.ToastUtils;
import com.yixin.ystartlibrary.widget.HintDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class OrderInfoActivity extends BaseAppCompatActivity {

    @BindView(R.id.ordernum)
    TextView ordernum;
    @BindView(R.id.goodsowner)
    TextView goodsowner;
    @BindView(R.id.goodsphone)
    TextView goodsphone;
    @BindView(R.id.goodstime)
    TextView goodstime;
    @BindView(R.id.goodsname)
    TextView goodsname;
    @BindView(R.id.drivername)
    TextView drivername;
    @BindView(R.id.driverphone)
    TextView driverphone;
    @BindView(R.id.card)
    TextView card;
    @BindView(R.id.goodsgeter)
    TextView goodsgeter;
    @BindView(R.id.getterphone)
    TextView getterphone;
    @BindView(R.id.geteraddress)
    TextView geteraddress;
    @BindView(R.id.staus)
    TextView staus;
    @BindView(R.id.picture)
    TextView picture;
    @BindView(R.id.recyclerview1)
    RecyclerView recyclerView1;
    @BindView(R.id.goods_bottom)
    Button goodsBottom;
    @BindView(R.id.over_bottom)
    Button overBottom;
    @BindView(R.id.goodsaddress)
    TextView goodsaddress;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    OrderAdapter orderAdapter;
    OrderAdapter1 orderAdapter1;
    OrderData.DataBean dataBean ;
    String flag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_info);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this.getWindow());
        StatusBarUtil.setPaddingSmart(this, mToolBar);
    }

    @Override
    protected void init() {
        settoolbar();
        initview();
    }

    private void settoolbar() {
        setCenterTitle("订单详情");
        setEnabledNavigation(true);

    }


    @OnClick(R.id.goodsphone)
    public void onGoodsphoneClicked() {
        showDialog(dataBean.getFJRDH(),dataBean.getFJR());

    }

    @OnClick(R.id.driverphone)
    public void onDriverphoneClicked() {
        showDialog(dataBean.getSJLXDH(),dataBean.getSJXM());
    }

    @OnClick(R.id.getterphone)
    public void onGetterphoneClicked() {
        showDialog(dataBean.getSJRDH(),dataBean.getSJR());
    }


    private  void  showDialog(final String phonenum, String name){
        final HintDialog hintDialog  = DialogUtils.createHintDialog(mActivity, phonenum+":"+name);
        hintDialog.setTitleText("是否拨打");
        hintDialog.setConfirmText("拨打");
        hintDialog.setCancelText("取消");
        hintDialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phonenum));
                if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
                    startActivity(intent);
                }
                if (hintDialog!=null&&hintDialog.isShowing())
                    hintDialog.dismiss();
            }
        });
        hintDialog.show();
    }



    private void initview() {
        LogUtils.i("initview");
        flag = getIntent().getStringExtra(Config.flags);
        if (TextUtils.equals(flag,"10")){//搜索订单flag =10
           String ordernum =getIntent().getStringExtra(Config.data);
        ApiManager.getInstence().getJmmApi().SearchOrder(GeneralPreferencesUtils.getSharedPreference(mActivity,Config.token,null),"10","1",ordernum)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        LogUtils.i("onSubscribe");
                    }

                    @Override
                    public void onNext(OrderData orderData) {
                        LogUtils.i("onNext");
                            if (orderData.getCount()==0)
                            {
                                ToastUtils.showLongToast(mActivity,"订单不存在了");
                                finish();
                                return;
                            }

                        LogUtils.i(orderData.getData().get(0).toString());
                        dataBean=orderData.getData().get(0);
                        LogUtils.i("databean==="+dataBean.toString());
                        setvalues(orderData.getData().get(0));
                        if (TextUtils.equals(dataBean.getZT(),"0"))
                            mMenu.findItem(R.id.mark_location).setVisible(false);
                        if (TextUtils.equals(dataBean.getZT(),"1"))
                            mMenu.findItem(R.id.mark_location).setVisible(false);
                        if (TextUtils.equals(dataBean.getZT(),"2"))
                            mMenu.findItem(R.id.mark_location).setVisible(true);
                        if (TextUtils.equals(dataBean.getZT(),"3"))
                            mMenu.findItem(R.id.mark_location).setVisible(true);
                        else if (TextUtils.equals(dataBean.getZT(),"4")){
                            mMenu.findItem(R.id.mark_location).setVisible(true);
                            mMenu.findItem(R.id.mark_location).setTitle("评分") ;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

        }else{
            dataBean = (OrderData.DataBean) getIntent().getSerializableExtra("data");
            LogUtils.i("flag"+flag);
            setvalues(dataBean);

        }

    }
    private  void setvalues(OrderData.DataBean dataBean){
        if (!TextUtils.isEmpty(dataBean.getDH()))
            ordernum.setText(dataBean.getDH());
        if (!TextUtils.isEmpty(dataBean.getFJR()))
            goodsowner.setText(dataBean.getFJR());
        if (!TextUtils.isEmpty(dataBean.getFJRDH()))
            goodsphone.setText(dataBean.getFJRDH());
        if (!TextUtils.isEmpty(dataBean.getDH()))
            goodstime.setText(dataBean.getFHSJ());
        if (!TextUtils.isEmpty(dataBean.getDH()))
            goodsaddress.setText(dataBean.getFJRDZ());
        if (!dataBean.getGOODSLIST().isEmpty()) {
            StringBuilder goodsName = new StringBuilder();
            for (OrderData.DataBean.GOODSLISTBean goodslistBean : dataBean.getGOODSLIST()) {
                goodsName = goodsName.append(goodslistBean.getMC()).append("|").append(goodslistBean.getSL()).append(goodslistBean.getDW()).append("  ");
            }
            goodsname.setText(goodsName);

        }
        if (TextUtils.isEmpty(dataBean.getSJXM()))
            drivername.setText("还未分配");
        else
            drivername.setText(dataBean.getSJXM());
        driverphone.setText(dataBean.getSJLXDH());
        card.setText(dataBean.getCPH());
        goodsgeter.setText(dataBean.getSJR());
        geteraddress.setText(dataBean.getSJRDZ());
        getterphone.setText(dataBean.getSJRDH());
        if (TextUtils.equals(dataBean.getZT(),"0"))
            staus.setText("未分配司机");
        if (TextUtils.equals(dataBean.getZT(),"1"))
            staus.setText("已分配司机");
        if (TextUtils.equals(dataBean.getZT(),"2"))
            staus.setText("未接货");
        if (TextUtils.equals(dataBean.getZT(),"3"))
            staus.setText("运输中");
        if (TextUtils.equals(dataBean.getZT(),"4"))
            staus.setText("已完成");

        initrecyclerview();
        List<OrderData.DataBean.JHFileListBean> jhFileListBeanList=dataBean.getJHFileList();
        List<String> lists =new ArrayList<>();
        lists.clear();
        for (int i=0;i<jhFileListBeanList.size();i++){

            LogUtils.i("接货"+jhFileListBeanList.get(i).getFJDZ());
            lists.add(jhFileListBeanList.get(i).getFJDZ());
        }
        List<String> list1= new ArrayList<>();
        List<OrderData.DataBean.HDFileListBean>  hdFileListBeans= dataBean.getHDFileList();
        list1.clear();
        for (int i=0;i<hdFileListBeans.size();i++){
            LogUtils.i("到货"+hdFileListBeans.get(i).getFJDZ());
            list1.add(hdFileListBeans.get(i).getFJDZ());
        }
        LogUtils.i("list.size=="+ lists.size()+"list1.size="+list1.size());
        orderAdapter.addInfoList(lists);
        orderAdapter.notifyDataSetChanged();
        orderAdapter1.addInfoList(list1);
        orderAdapter1.notifyDataSetChanged();
    }

    private  void  initrecyclerview(){
        orderAdapter = new OrderAdapter();
        orderAdapter1 = new OrderAdapter1();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.setAdapter(orderAdapter);
        recyclerView1.setLayoutManager(linearLayoutManager1);
        recyclerView1.setAdapter(orderAdapter1);
    }






    public class OrderAdapter extends BaseRecyclerAdapter<String, OrderAdapter.ViewHolder> {

        @Override
        protected void onBindViewHolder(int position, ViewHolder holder) {
                String url = getItem(position);
             holder.setphoto(Config.URL_JMMURL+url);
        }

        @Override
        protected void onBindItemClickListener(View v, int position) {
            super.onBindItemClickListener(v, position);
                Intent intent = new Intent(mActivity,PicActivity.class);
                    intent.putExtra("data", (Serializable) getAllInfoList());
                        intent.putExtra("position",position);
                       startActivity(intent);

        }

        @Override
        protected ViewHolder getViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(inflate(R.layout.item_oderpicture, parent));
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.photo)
            AppCompatImageView photo;
            @BindView(R.id.relative)
            RelativeLayout relativeLayout ;

            ViewHolder(View view) {
                super(view);

                ButterKnife.bind(this, view);
            }


            private void setphoto(String string) {
                RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(
                        (int) (DensityUtil.getWidth(mActivity) / 3), RelativeLayout.LayoutParams.WRAP_CONTENT);
                LogUtils.i("width=" + l.width);
                l.setMargins(10, 0, 0, 0);  //设置间距
                l.height = (int) (l.width);
                photo.setLayoutParams(l);
                ImageUtil.displayDefault(mActivity, string, photo);
            }

        }
    }
    public class OrderAdapter1 extends BaseRecyclerAdapter<String, OrderAdapter1.ViewHolder> {

        @Override
        protected void onBindViewHolder(int position, ViewHolder holder) {
                String url = getItem(position);
                LogUtils.i(Config.URL_JMMURL+url);
             holder.setphoto(Config.URL_JMMURL+url);

        }

        @Override
        protected void onBindItemClickListener(View v, int position) {
            super.onBindItemClickListener(v, position);
            Intent intent = new Intent(mActivity,PicActivity.class);
            intent.putExtra("data", (Serializable) getAllInfoList());
            intent.putExtra("position",position);
            startActivity(intent);

        }

        @Override
        protected ViewHolder getViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(inflate(R.layout.item_oderpicture, parent));
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.photo)
            AppCompatImageView photo;
            @BindView(R.id.relative)
            RelativeLayout relativeLayout ;

            ViewHolder(View view) {
                super(view);

                ButterKnife.bind(this, view);
            }


            private void setphoto(String string) {
                RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(
                        (int) (DensityUtil.getWidth(mActivity) / 3), RelativeLayout.LayoutParams.WRAP_CONTENT);
                LogUtils.i("width=" + l.width);
                l.setMargins(10, 0, 0, 0);  //设置间距
                l.height = (int) (l.width);
                photo.setLayoutParams(l);
                ImageUtil.displayDefault(mActivity, string, photo);
            }

        }
    }

    Menu mMenu ;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        LogUtils.i("onOptionsItemSelected");
        switch (item.getItemId()){
            case  R.id.mark_location:
                if (TextUtils.equals(dataBean.getZT(),"4"))//3已完成
                {
                  /*  Intent intent= new Intent(this, GradeActivity.class);
                    intent.putExtra(Config.data,dataBean);
                    startActivity(intent);*/
                } else {
                        if (mLocationListener!=null){
                            Intent intent= new Intent(mActivity, MainActivity.class);
                            intent.putExtra(Config.data,dataBean);
                            startActivity(intent);
                            Intent   intent1 = new Intent(this,ControlService.class);
                            intent1.putExtra(Config.flags,0);
                            startService(intent1);
                            GeneralPreferencesUtils.setSharedPreference(this,Config.tip,dataBean.getXH());
                            mLocationListener.location();
                        }

                    /*intent.putExtra(Config.data,dataBean);
                    this.setResult(RESULT_OK, intent);*/


                }
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        LogUtils.i("onCreateOptionsMenu");
        getMenuInflater().inflate(R.menu.mark_location,menu);

        return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        LogUtils.i("onPrepareOptionsMenu");
        if (TextUtils.equals(flag,"10")){
            mMenu=menu;

            return true;
        }

        if (TextUtils.equals(dataBean.getZT(),"0"))
        menu.findItem(R.id.mark_location).setVisible(false);
        if (TextUtils.equals(dataBean.getZT(),"1"))
        menu.findItem(R.id.mark_location).setVisible(false);
        if (TextUtils.equals(dataBean.getZT(),"2"))
        menu.findItem(R.id.mark_location).setVisible(true);
        if (TextUtils.equals(dataBean.getZT(),"3"))
        menu.findItem(R.id.mark_location).setVisible(true);
        else if (TextUtils.equals(dataBean.getZT(),"4")){
            menu.findItem(R.id.mark_location).setVisible(false);
            menu.findItem(R.id.mark_location).setTitle("评分") ;
        }
        return super.onPrepareOptionsMenu(menu);
    }


    public interface LocationLister {
        void  location();
    }

    private   static LocationLister mLocationListener ;
    public  static  void setLocationLister(LocationLister locationLister){
            mLocationListener=locationLister;

    }
    public interface MarkLister {
        void  successful();
    }




}
